<template>
  <section class="todoapp">
    <!-- 使用组件，并且传递给组件对应方法 -->
    <TodoHeader @addTask="addTaskFn" :arr="showList"></TodoHeader>
    <TodoMain :arr="showList" @del="delTaskFn"></TodoMain>
    <TodoFooter
      @curShow="getShowType"
      @delCom="delComFn"
      :arr="showList"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";
//引入组件 头部 身体 腿部
import TodoHeader from "./components/TOdo/TodoHeader.vue";
import TodoMain from "./components/TOdo/TodoMain.vue";
import TodoFooter from "./components/TOdo/TodoFooter.vue";

export default {
  //注册组件 头部 身体 腿部
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 100, name: "吃烤面筋", isDone: true },
      //   { id: 102, name: "开向日葵", isDone: false },
      //   { id: 103, name: "吃钵仔糕", isDone: true },
      // ],
      list: JSON.parse(localStorage.getItem("lists")) || [],
      curType: "all", //当前显示的类型，默认全部
    };
  },
  watch: {
    list: {
      deep: true,
      handler(newStr) {
        localStorage.setItem("lists", JSON.stringify(newStr));
      },
    },
  },
  methods: {
    //新增任务
    addTaskFn(name) {
      //如果下标存在，那么获取最后一个元素的下标赋值给id，如果没有下标则直接赋值100给id
      let id =
        (this.list.length && this.list[this.list.length - 1].id + 1) || 100;
      this.list.push({
        id,
        name,
        isDone: false,
      });
    },
    //删除按钮
    delTaskFn(index) {
      this.list.splice(index, 1);
    },
    //切换显示任务
    getShowType(type) {
      console.log(type);
      this.curType = type;
    },
    //清除已完成
    delComFn() {
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].isDone) {
          this.list.splice(i, 1);
          i--;
        }
      }
    },
  },
  computed: {
    //筛选显示对应的的任务列表 yes=已完成，no=未完成，剩下是全部
    showList() {
      if (this.curType === "yes") {
        return this.list.filter((item) => item.isDone);
      } else if (this.curType === "no") {
        return this.list.filter((item) => !item.isDone);
      } else {
        return this.list;
      }
    },
  },
};
</script>
1